<script setup lang="ts">
import type { TRoute } from '~comp/breadcrumb/Breadcrumb.vue';
import type { DepositDetail } from '~/api/services/main.api';
import failedIcon from '~/assets/icons/deposit-result-failed.svg';
import resultIcon from '~/assets/icons/deposit-result-icon.svg';
import successIcon from '~/assets/icons/deposit-result-success.svg';
import cs from '~/composables/useCS';
import { noticeMeta } from '~/composables/useMeta';

export interface PayResultProps {
  status?: 'success' | 'failed' | 'pending';
  orderNo?: string;
  orderInfoData?: DepositDetail;
  onClose?: () => void;
};

const props = defineProps<PayResultProps>();

const router = useRouter();

const getBreadcrumbRef = computed((): TRoute[] => [[$t('dufTiBp3d_6nPxfaj053J'), toValue(router.currentRoute)]]);

const getOrderNoRef = computed(() => props.orderNo || router.currentRoute.value.query?.order_no as string || '');

const enabledRef = ref(false);

async function getPayResult() {
  if (!getOrderNoRef.value)
    return void 0;

  const res: any = await apis.apiFundDepositQuery(
    { order_no: getOrderNoRef.value },
    { errorMessage: false, checkCode: false, resultType: 'axios' },
  );
  const resData = res?.data;
  if (resData?.code === 0) {
    const data = resData?.data;
    if (data && [1, 2, 5].includes(data?.status)) {
      enabledRef.value = false;
      if (data?.status === 1) {
        useCurrencyStore().balanceQry.refetch();
        noticeMeta().deposit({ currency: 'PHP', value: data.amount });
      }
    }
    return data;
  }
  if (resData?.code === 17025) {
    return { status: 2 };
  }
  return void 0;
}

const orderInfoQry = useQuery({
  enabled: enabledRef,
  queryKey: [apis.apiFundDepositQuery.id, getOrderNoRef],
  queryFn: getPayResult,
  refetchInterval: ({ state: { data } }) => [1, 2, 5].includes(data?.status) ? false : 3000,
});

watch(getOrderNoRef, (v) => {
  enabledRef.value = !!v;
}, { immediate: true });

const getOrderInfoDataRef = computed(() => {
  const data = toValue(orderInfoQry.data) || props.orderInfoData;
  const { create_time, amount, currency, status: rStatus } = router.currentRoute.value.query as Record<string, string>;
  const time = bignumber(data?.create_time || create_time || 0).toNumber();
  const status = data?.status === 1 ? 'success' : [3, 4].includes(data?.status || 0) ? 'pending' : 'failed';
  return {
    status: data ? status : rStatus || 'pending',
    orderNo: data?.order_no || getOrderNoRef.value,
    createTime: time ? $d(time, 'full') : '-',
    amount: data?.amount || amount ? bignumber(data?.amount || amount).toFormat() : '',
    currency: data?.currency?.currency || data?.currency || currency || '',
  };
});

const getInfoRef = computed(() => {
  const { status: rStatus } = router.currentRoute.value.query as Record<string, string>;
  const { status: statusRef } = getOrderInfoDataRef.value;
  const isSuccess = props.status === 'success' || rStatus === 'success' || statusRef === 'success';
  return {
    isSuccess,
    iconUrl: isSuccess ? successIcon : statusRef === 'pending' ? resultIcon : failedIcon,
    iconCls: statusRef === 'pending' ? 'h-15' : 'h-40',
    title: isSuccess ? $t('lNyZGuE_0cb9lNdWj8cJf') : statusRef === 'pending' ? $t('177YjDwxyfdqa4gZi2Bcx') : $t('2ccLzS7isx1fEdRySbnCp'),
    subtitle: isSuccess ? $t('gqra69EtrqxHwCvhyXLn') : $t('ksxFycYsfcl9eJd5Ae3E'),
  };
});

const { handshake, isAgent } = storeToRefs(useAppStore());

const getCsNameRef = computed(() => {
  if (isAgent.value) {
    return handshake.value?.telegram_customer_id;
  }

  return $t('vDq3LxKOtvPpIbmWnfOo8');

  const csType = handshake.value?.customer_type;
  if (csType === 1)
    return handshake.value?.telegram_customer_id;
  if (csType === 2)
    return $t('vDq3LxKOtvPpIbmWnfOo8');
  return '';
});

function toDetailsPage() {
  props.onClose?.();
  router.replace({ name: RN.USER_TRANSATIONS, query: { active: 0 } });
}

function backHome() {
  router.replace({ name: RN.INDEX });
}
</script>

<template>
  <div class="main-auto-height w-full">
    <div class="tablet:(mx-auto mt-16 max-w-[78%])">
      <div
        class="mb-6 h-10 w-fit flex-center cursor-pointer rounded-lg bg-sys-layer-d px-4 text-base text-sys-text-body tablet:mb-10 hover:text-sys-text-head"
        @click="backHome"
      >
        <i class="i-ep:arrow-left-bold text-sys-head h-4.5 w-4.5" />
        <div>Back</div>
      </div>

      <div class="flex-center">
        <div class="text-sm text-sys-text-body tablet:(max-w-120 min-w-100)">
          <div class="flex-center">
            <img :src="getInfoRef.iconUrl" :class="getInfoRef.iconCls">
          </div>
          <div class="mb-2 mt-6 text-center text-xl text-sys-text-head">
            {{ getInfoRef.title }}
          </div>
          <div class="text-center">
            <span>{{ getInfoRef.subtitle }}</span>
            <span
              v-if="getInfoRef.isSuccess" class="ml-1 cursor-pointer text-red underline"
              @click="toDetailsPage"
            >{{ $t('tp79aKotH5sDKwZhDn44B') }} </span>
          </div>

          <div class="mb-3 mt-8 h-[1px] bg-sys-layer-d" />

          <div class="grid grid-cols-[auto_1fr] mb-2 gap-2">
            <div>{{ $t('wo9Lgc1igeGepW9Bi6O24') }}</div>
            <div v-if="getOrderInfoDataRef.orderNo" class="grid grid-cols-[1fr_auto] w-full gap-2 text-sys-text-head">
              <div class="break-all text-right">
                {{ getOrderInfoDataRef.orderNo }}
              </div>
              <TCopy :source="getOrderInfoDataRef.orderNo" :nthParent="1" />
            </div>
            <div v-else class="text-right text-sys-text-head">
              -
            </div>

            <div>{{ $t('xoYirzOqk0ri8i18vC6Z6') }}</div>
            <div class="text-right text-sys-text-head">
              {{ getOrderInfoDataRef.createTime }}
            </div>

            <div>{{ $t('gISik9oabNrFv20d9znt') }}</div>
            <div v-if="getOrderInfoDataRef.amount" class="text-right text-green">
              {{ `${getOrderInfoDataRef.amount} ${getOrderInfoDataRef.currency}` }}
            </div>
            <div v-else class="text-right text-sys-text-head">
              -
            </div>

            <div>{{ $t('4Kk4qMiIl1q9zmuCQwD1X') }}</div>
            <div class="text-right text-sys-text-head">
              <span v-if="getCsNameRef" class="cursor-pointer text-red underline" @click="cs.show">{{ getCsNameRef }}</span>
              <span v-else>-</span>
            </div>
          </div>
        </div>
      </div>
    </div>

    <div class="mt-16 tablet:(mx-auto mt-20 max-w-[88%]) !mb-5">
      <TBreadcrumb :routes="getBreadcrumbRef" />
    </div>
  </div>
</template>
